package com.example.aicloud.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 创建线程池
 */
@Configuration
public class ThreadPoolConfig {
    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors()+1); //当前cpu核心数加一，加一的原因是时刻准备一个预备线程，充分利用cpu资源
        executor.setMaxPoolSize(2*Runtime.getRuntime().availableProcessors()+1); // 核心线程数2倍加1
        executor.setQueueCapacity(100000); // 任务队列容量
        executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {  //自定义拒绝策略
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                // 1. 保存拒绝的任务
                // 2. 通知相关负责人手动处理
            }
        });
        executor.initialize(); // 初始化
        return executor;
    }
}
